package com.zja.util;

import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Properties;
import java.sql.Connection;

public class DBConnectionPool {
    // 连接池
    private static LinkedList<Connection> pool = new LinkedList<>();

    // 配置参数
    private static String URL;
    private static String USER;
    private static String PASSWORD;
    private static int INIT_POOL_SIZE;

    static {
        try {
            // 读取配置文件
            Properties properties = new Properties();
            InputStream in = DBConnectionPool.class.getClassLoader().getResourceAsStream("db.properties");
            properties.load(in);

            URL = properties.getProperty("db.url");
            USER = properties.getProperty("db.username");
            PASSWORD = properties.getProperty("db.password");
            INIT_POOL_SIZE = Integer.parseInt(properties.getProperty("db.initPoolSize"));

            // 注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 初始化连接池
            for (int i = 0; i < INIT_POOL_SIZE; i++) {
                pool.add(createConnection());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 创建新连接的方法
    private static Connection createConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }

    // 获取连接
    public static synchronized Connection getConnection() throws SQLException {
        if (pool.isEmpty()) {
            throw new SQLException("连接池耗尽！");
        }
        return pool.removeFirst();
    }

    // 归还连接
    public static synchronized void releaseConnection(Connection connection) {
        if (connection != null) {
            pool.addLast(connection);
        }
    }
}
